$(function() {
	$(document).ready(function() {
		$.eva.__init();
	});
});

(function($){
	var b = {};
	b.content = {};
	b.eva = {};
	b.message = {};
	b.tooltip = {}
	
	var s = {};
	s.template =	'<div class="eva-container">'+
				'<div class="eva-container-inner">'+
					'<div class="avatar" eva-content="Drag me!"></div>'+
					'<div class="message">'+
						'<div class="message-content">'+
							'<div class="title"></div>'+
							'<div class="text"></div>'+
							'<div class="cont"></div>'+
						'</div>'+
						'<div class="tooltip-content">'+
							'<div class="title"></div>'+
							'<div class="text"></div>'+
						'</div>'+
					'</div>'+
				'</div>'+
			'</div>';
	
	s.formTemplate = '<div class="eva-slider"><div class="slides"></div><div class="slider-nav"><div class="prev"><span class="btn btn-minus"></span></div><div class="dots"></div><div class="next"><span class="btn btn-plus"></span></div></div></div>';
	s.timerShow = false;
	s.showStatus = false;
	s.timerHide = false;
	
	var eva = {
		__init : function() {
			b.content = $('.main-container');
			
			
			if(!b.content.find('.eva-container').length) {
				b.content.append(s.template);
				
			}
			
			b.eva = $('.eva-container');
			b.message = b.eva.find('.message-content');
			b.tooltip = b.eva.find('.tooltip-content');
			
			// init content from view
			if($('.eva-content').length) {
				b.message.find('.cont').append($('.eva-content').children());
			}
			
			// init form elements
			$('.checkbox').each(function() {
				$(this).children('input').change(function() {
					var $this = $(this);
					if($this.is(':checked')) {
						$this.parent().addClass('checked');
					} else {
						$this.parent().removeClass('checked');
					}
				});
				$(this).children('input').change();
			});
			
			// drag
			$('.eva-container').draggable({
				handle: '.avatar',
				containment: '.main-container',
				appendTo: '.main-container',
				drag: function() {
					var $this = $(this);
					var bodyWidth = $('.main-container').width();
					var evaW = $this.width();
					var offsetX = $this.offset().left;
					
					if(offsetX < (bodyWidth/2 - evaW/2)) {
						$this.addClass('left-side');
					} else {
						$this.removeClass('left-side');
					}
				},
				stop: function() {
					var $this = $(this);
					$.cookie('eva-position-x', $this.position().left, {'path': '/'});
					$.cookie('eva-position-y', $this.position().top, {'path': '/'});
					$.cookie('eva-position-side', ($this.hasClass('left-side') ? 'left-side' : ''), {'path': '/'});
				}
			});
			
			// init eva tooltips
			$('[eva-content]').hover(function() {
				var $this = $(this);
				var title = $this.attr('eva-title');
				var text = $this.attr('eva-content');

//				if(b.eva.has($this)) {
//					
//				} else {
					if(s.showStatus) {
						
						if(s.timerHide) {
							window.clearTimeout(s.timerHide);
							s.timerHide = false;
						}
						eva.say(text, title);
					} else {
						
						s.timerShow = window.setTimeout(function() {
							window.clearTimeout(s.timerShow);
							s.timerShow = false;
							
							eva.say(text, title);
						}, 400);
					}
//				}
			}, function() {
				if(s.timerShow == false) {
					if(s.showStatus) {
						s.timerHide = window.setTimeout(function() {
							eva.setOriginal();
						}, 1000);
					} else {
						
					}
				} else {
					window.clearTimeout(s.timerShow);
					s.timerShow = false;
				}
			});
			
			// paginator
			$('.ajaxPager').click(function() {
				var $this = $(this);
				if($this.hasClass('isLoading')) {
					return false;
				}
				
				$this.addClass('isLoading');
				$.ajax({
					url: $this.attr('href'),
					type: "POST",
					dataType: 'json',
					data: {'forPaginator': true},
					success : function(resp) {
						if(resp.page) {
							$this.attr('href', resp.page);
							$this.removeClass('isLoading');
						} else {
							$this.remove();
						}
						
						$('.ajaxPagerContent').append(resp.content);
					},
					error : function() {
						
					}
				});
				return false;
			});
			
			eva.open();
		},
		
		open : function() {
			var x = $.cookie('eva-position-x');
			var y = $.cookie('eva-position-y');
			
			// set predefined width
			if(typeof(evaWidth) != 'undefined') {
				b.eva.css('width', evaWidth);
			}
			
			var evaW = b.eva.width();
			var evaH = b.eva.height();
			
			var bodyW = $('body').width();
			var bodyH = $('body').height();
			
			var maxX = bodyW - evaW - 10;
			var maxY = bodyH - evaH - 10;
			
			// set from cookie or in position by default
			x = (x == null) ? maxX : (x > maxX ? maxX : x);
			y = (y == null) ? maxY : (y > maxY ? maxY : y);
			
			// set predefined position
			if(typeof(evaPosition) != 'undefined') {
				switch(evaPosition) {
					case 'center':
						x = parseInt((bodyW - evaW)/2);
						y = parseInt((bodyH + evaH)/2);
						break;
					default:
						break;
				}
			}
			
			// set side of eva
			if((bodyW - evaW)/2 >= x) {
				b.eva.addClass('left-side');
			}
			
			y+='px';x+='px';
			
			// set message
			if(typeof(evaTitle) != 'undefined') {
				b.message.find('.title').html(evaTitle);
			}
			if(typeof(evaMessage) != 'undefined') {
				b.message.find('.text').html(evaMessage);
			}
			
			// init form application
			if($('.eva-slider-form').length) {
				eva.initForm($('.eva-slider-form'));
			}
			
			b.eva.css({
				'top': y,
				'left': x
			});
			
			b.eva.fadeIn(500);
		},
		
		initForm : function($form) {
			var contentShowed = false;
			var $c = b.eva.find('.cont');
			$c.empty().hide().append(s.formTemplate);
			
			var $slides = $c.find('.slides');
			var $nav = $c.find('.slider-nav');
			var $dots = $nav.find('.dots');
			var $sliderContent = $('.eva-slider-content').children();
			
			// move slider-form to eva
			$slides.append($form);
			$slides.find('fieldset').each(function() {
				$dots.append('<span></span>');
				if($(this).find('.autoform-element-errors').length) {
					$dots.children().last().addClass('red');
				}
			});
			
			$c.show();
			
			// listeners for form element
			$c.find('input, select, textarea').focus(function() {
				if(!contentShowed) {
					contentShowed = true;
					$('.eva-slider-content').fadeIn(300);
				}
				var $el = $sliderContent.find('span[data-name="'+$(this).attr('id')+'"]').parent().parent();
				
				$el.addClass('selected');
			});
			$c.find('input, select, textarea').blur(function() {
				
				$sliderContent.find('.row.selected').removeClass('selected');
			});
			$c.find('input, textarea').keyup(function() {
				var val = $(this).val();
				if($(this).attr('type') == 'password') {
					val = val.replace(/./g, '*');
				}
				$sliderContent.find('span[data-name="'+$(this).attr('id')+'"]').text(val);
			});
			$c.find('select').change(function() {
				var val = $(this).children('option:selected').text();
				$sliderContent.find('span[data-name="'+$(this).attr('id')+'"]').text(val);
			});
			
			// listeners for dots
			$dots.children('span').click(function() {
				var $this = $(this);
				$dots.find('.active').removeClass('active');

				var active = $this.index();

				if(active == 0) {
					$nav.find('.prev').addClass('disabled');
				} else {
					$nav.find('.prev').removeClass('disabled');
				}

				if(active == $dots.children().length - 1) {
					$nav.find('.next').addClass('disabled');
				} else {
					$nav.find('.next').removeClass('disabled');
				}

				$this.addClass('active');
				$slides.find('fieldset.active').removeClass('active');

				var $activeFieldset = $slides.find('fieldset').eq(active);
				$activeFieldset.addClass('active');

				$sliderContent.children('.active').removeClass('active');
				$sliderContent.children('.fieldset[data-name="'+$activeFieldset.attr('id')+'"]').addClass('active');

				return false;
			});

			$sliderContent.find('.edit-fieldset').click(function() {
				var index = $(this).parent().index();
				if($sliderContent.children('.title').length) {
					index--;
				}
				$dots.children().eq(index).click();

				return false;
			});
			
			// init next\prev buttons
			$nav.find('.prev, .next').click(function () {
				if($(this).hasClass('disabled')) {
					return false;
				}

				var active = $dots.children('.active').index();

				if($(this).hasClass('next')) {
					$dots.children('.active').next().click();
				} else {
					$dots.children('.active').prev().click();
				}

				return false;
			});

			$dots.children().first().click();
		},
		
		say : function(text, title) {
			b.tooltip.children('.text').html(text);
			b.tooltip.children('.title').html((typeof(title) != 'undefined') ? title : 'Quick help');
			
			s.showStatus = true;
			eva.setTooltip(b.message, b.tooltip);
		},
		
		setOriginal : function() {
			s.showStatus = false;
			eva.setTooltip(b.tooltip, b.message);
		},
		
		setTooltip : function($hide, $show) {
			$hide.stop(true).fadeTo(0, 0, function() {
				$(this).hide(0);
				$show.stop(true).fadeTo(0, 1);
			});
		}
	}

	$.extend({
		eva:eva
	});
	
	$.cookie = function(key, value, options) {
		// key and at least value given, set cookie...
		if (arguments.length > 1 && (!/Object/.test(Object.prototype.toString.call(value)) || value === null || value === undefined)) {
			options = $.extend({}, options);

			if (value === null || value === undefined) {
				options.expires = -1;
			}

			if (typeof options.expires === 'number') {
				var days = options.expires, t = options.expires = new Date();
				t.setDate(t.getDate() + days);
			}

			value = String(value);

			return (document.cookie = [
				encodeURIComponent(key), '=', options.raw ? value : encodeURIComponent(value),
				options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
				options.path ? '; path=' + options.path : '',
				options.domain ? '; domain=' + options.domain : '',
				options.secure ? '; secure' : ''
			].join(''));
		}

		// key and possibly options given, get cookie...
		options = value || {};
		var decode = options.raw ? function(s) {return s;} : decodeURIComponent;

		var pairs = document.cookie.split('; ');
		for (var i = 0, pair; pair = pairs[i] && pairs[i].split('='); i++) {
			if (decode(pair[0]) === key) return decode(pair[1] || ''); // IE saves cookies with empty string as "c; ", e.g. without "=" as opposed to EOMB, thus pair[1] may be undefined
		}
		return null;
	};
})(jQuery)

